package dialer.ws.security.service.impl;

import java.util.ArrayList;
import java.util.Collection;

import javax.annotation.Resource;
import javax.persistence.NoResultException;

import org.apache.log4j.Logger;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import dialer.client.web.controlador.LoginController;
import dialer.ws.base.entity.vtelcom.Usuario;
import dialer.ws.base.exception.EntityException;
import dialer.ws.base.exception.EntityNoFoundException;
import dialer.ws.base.query.NamedQueryParameter;
import dialer.ws.business.dao.UsuarioDAO;
import dialer.ws.common.util.FacesUtils;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

	protected Logger log = Logger.getLogger(getClass());

	@Resource(name = "usuarioDAO")
	private UsuarioDAO usuarioDAO;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		log.info("### loadUserByUsername");
		try {
			NamedQueryParameter param = new NamedQueryParameter("username", username);
			Usuario usuario = usuarioDAO.findInstanceByNamedQueryNamedParameter("Usuario.findByUserName", param);
			log.info("### usuario " + usuario.getUsername());
			LoginController login = (LoginController) FacesUtils.getManagedBean("login");
			if(usuario.equals(null)) {
				login.setError("Usuario no existe");
			}
			
			if (!usuario.getUsername().equals(login.getUsuario().getUsername())) {
				login.setError("Password Incorrecto");
			}
			login.setUsuario(usuario);
			
			boolean enabled = true;
			boolean accountNonExpired = true;
			boolean credentialsNonExpired = true;
			boolean accountNonLocked = true;

			Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
			grantedAuthorities.add(new GrantedAuthorityImpl("ROLE_" + usuario.getRole().getName()));

			User userdetail = new User(usuario.getUsername(), usuario.getPassword(), enabled, accountNonExpired, credentialsNonExpired,
					accountNonLocked, grantedAuthorities);
			return userdetail;
		} catch (EntityException e) {
			throw new BadCredentialsException("Credenciales invalidas");
		} catch (EntityNoFoundException e) {
			throw new BadCredentialsException("Credenciales invalidas");
		} catch (NoResultException e) {
			throw new UsernameNotFoundException("user " + username + " no encontrado");
		}

	}

}
